//
//  GROderDetailViewController.m
//  YC_GRice
//
//  Created by luojinrong11 on 2018/7/23.
//  Copyright © 2018年 YeCai. All rights reserved.
//

#import "GROderDetailViewController.h"
#import "GRGoodTableViewCell.h"
#import "GROderDetailAddrCell.h"
#import "GROderDetailFootView.h"
#import "GRConfirmSectionHeaderView.h"
#import "GRStageDetailTableViewCell.h"
#import "GROederDetailHeaderCell.h"
#import "GROrderManagerAction.h"
#import "GROrderListModel.h"
#import "GRPayDetailCell.h"
#import "GROrderDetailGoodCell.h"

#import "GRLogisticsInforViewController.h"
#import "GRReturnGoodView.h"
#import "GRReturnReasonView.h"
#import "RequestManager+GROrderManager.h"
#import "GROrderTraceView.h"
#import "GRReturnViewController.h"
#import "GROrderCommentViewController.h"
#import "GRPurchaseSuccessViewController.h"

typedef NS_ENUM(NSInteger,DetailCellType){
    DetailCellTypeStatusCell = 0,
    DetailCellTypeAddressCell,
    DetailCellTypeGoodsCell,
    DetailCellTypeStageCell,
    DetailCellTypePayCell,
    DetailCellTypeInvoiceCell,
    DetailCellOderDetailell
};

@interface GROderDetailViewController ()<UITableViewDataSource,UITableViewDelegate,GROrderManagerProto,GRReturnGoodViewDelegate,GRReturnReasonViewDelegate>
{
    NSInteger returnOrderId;
}
@property (weak, nonatomic) IBOutlet UITableView *detailList;
@property(nonatomic,strong)GROrderManagerAction* detailAction;
@property(nonatomic,strong)NSMutableDictionary * returnDic;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property(nonatomic,strong)GROrderListModel * listModel;
@property(nonatomic,strong)NSArray * stageLeftArr;
@property(nonatomic,strong)NSArray * stageRightArr;
@property(nonatomic,strong)NSArray *  invoiceLeftArr;
@property(nonatomic,strong)NSArray * invoiceRightArr;
@property(nonatomic,strong)NSArray * orderRightArr;
@property(nonatomic,strong)NSArray * orderLeftArr;
@property(nonatomic,strong)NSArray * payArr;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topOffset;
@property(nonatomic,strong)NSArray * CellArr;


@end

@implementation GROderDetailViewController

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.barTintColor = KGMTHEM_COLOR;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault]; // 此处的[UIImage new]可以替换成图片
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
 
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:nil];
}

-(NSMutableDictionary *)returnDic{
    if (!_returnDic) {
        _returnDic = [NSMutableDictionary dictionary];
    }
    return _returnDic;
}

-(GROrderManagerAction *)detailAction{
    if (!_detailAction) {
        _detailAction = [[GROrderManagerAction alloc]init];
    }
    return _detailAction;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.topOffset.constant = IS_IPHONEX?88:64;
    self.stageLeftArr = @[@"首付金额",@"分期金额",@"分期信息",@"月供(实际还款以账单为准)"];
    self.invoiceLeftArr = @[@"发票类型",@"发票抬头",@"手机号码",@"发票内容"];
    self.orderLeftArr = @[@"订单编号",@"订单时间"];
    // Do any additional setup after loading the view from its nib.
    [self.detailList registerNib:[UINib nibWithNibName:@"GROrderDetailGoodCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"goodCell"];
    [self.detailList registerNib:[UINib nibWithNibName:@"GROderDetailAddrCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"addressCell"];
    [self.detailList registerNib:[UINib nibWithNibName:@"GRStageDetailTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"detailCell"];
    [self.detailList registerNib:[UINib nibWithNibName:@"GROederDetailHeaderCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"headerCell"];
    [self.detailList registerNib:[UINib nibWithNibName:@"GRPayDetailCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"PayCell"];
    [self loadData];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(loadData) name:@"paySuucess" object:nil];
}

-(void)loadData{
    [self.detailAction requestOrderDetail:self.orderId CallBack:^(GROrderListModel *listModel, GRError *error) {
 
        if (!error) {
      
        self.listModel = listModel;
        self.stageRightArr = @[[NSString stringWithFormat:@"￥%.2lf",self.listModel.firstMoney],[NSString stringWithFormat:@"￥%.2lf",self.listModel.alertPay],[NSString stringWithFormat:@"%ld",self.listModel.totalStages],[NSString stringWithFormat:@"￥%.2lf",self.listModel.monthProvide]];
        self.invoiceRightArr = @[(self.listModel.invoiceFlg == 0?@"电子发票":@"纸质发票"),( self.listModel.invoiceType == 0 ?@"个人":@"公司"),self.listModel.receiveMobile,@"商品明细"];
        self.orderRightArr = @[self.listModel.orderSn,self.listModel.createdAtStr];
        NSString * payStr;
        if (self.listModel.payType == 1) {
            payStr = @"微信";
        }else if (self.listModel.payType == 2){
            payStr = @"支付宝";
        }else if (self.listModel.payType == 3){
            payStr = @"龟米";
        }else{
             payStr = @"龟米小程序";
        }
        self.payArr = @[[NSString stringWithFormat:@"%.2lf", self.listModel.price],   [NSString stringWithFormat:@"-%.2lf",  self.listModel.payPoint],payStr];
        if (listModel.status == 1) {
            if (listModel.invoice) {
                  self.CellArr = @[@(DetailCellTypeStatusCell),@(DetailCellTypeAddressCell),@(DetailCellTypeGoodsCell),@(DetailCellTypeInvoiceCell),@(DetailCellOderDetailell)];
            }else{
                 self.CellArr = @[@(DetailCellTypeStatusCell),@(DetailCellTypeAddressCell),@(DetailCellTypeGoodsCell),@(DetailCellOderDetailell)];
            }
        }else{
            if (listModel.invoice ) {//账单，分期都有
                if (listModel.byStages) {
                    self.CellArr = @[@(DetailCellTypeStatusCell),@(DetailCellTypeAddressCell),@(DetailCellTypeGoodsCell), @(DetailCellTypeStageCell),@(DetailCellTypePayCell),@(DetailCellTypeInvoiceCell),@(DetailCellOderDetailell)];
                }else{
                self.CellArr = @[@(DetailCellTypeStatusCell),@(DetailCellTypeAddressCell),@(DetailCellTypeGoodsCell), @(DetailCellTypePayCell),@(DetailCellTypeInvoiceCell),@(DetailCellOderDetailell)];
                }
            }else{
                if (listModel.byStages) {
                    self.CellArr = @[@(DetailCellTypeStatusCell),@(DetailCellTypeAddressCell),@(DetailCellTypeGoodsCell), @(DetailCellTypeStageCell),@(DetailCellTypePayCell),@(DetailCellOderDetailell)];
                }else{
                self.CellArr = @[@(DetailCellTypeStatusCell),@(DetailCellTypeAddressCell),@(DetailCellTypeGoodsCell), @(DetailCellTypePayCell),@(DetailCellOderDetailell)];
                }
            }
        }
        [self.detailList reloadData];
        [self updateTitle];
        }else{
            [error errorAlertWithUIView:self.view offsetY:50 completion:^{
                [self loadData];
            }];
        }
    }];
}

-(void)updateTitle{
    NSString * statuStr;
    switch (self.listModel.status) {
        case 10:
            statuStr = @"订单已取消";
            break;
        case 1:
            statuStr = @"等待支付";
            break;
        case 3:
            statuStr = @"等待发货";
            break;
        case 5:
             statuStr = @"等待收货";
           
            break;
        case 9:
            statuStr = @"已完成";
            break;
        default:
            statuStr = @"未知订单状态";
            break;
    }
    self.titleLabel.text = statuStr;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    DetailCellType cellType = [self.CellArr[indexPath.section] integerValue];
    if ( cellType == DetailCellTypeStatusCell) {
        GROederDetailHeaderCell * headerCell = [tableView dequeueReusableCellWithIdentifier:@"headerCell" forIndexPath:indexPath];
        headerCell.orderListModel = self.listModel;
        headerCell.delegate = self;
        return headerCell;
    }else if (cellType == DetailCellTypeAddressCell){
        GROderDetailAddrCell * addressCell = [tableView dequeueReusableCellWithIdentifier:@"addressCell" forIndexPath:indexPath];
        addressCell.listModel = self.listModel;
        return addressCell;
    }else if(cellType == DetailCellTypeGoodsCell){
       GROrderDetailGoodCell * goodCell = [tableView dequeueReusableCellWithIdentifier:@"goodCell" forIndexPath:indexPath];
        goodCell.goodModel = self.listModel.goods[indexPath.row];
        goodCell.delegate = self;
        return goodCell;
    }else if(cellType == DetailCellTypeStageCell){
        
        GRStageDetailTableViewCell * stageCell = [tableView dequeueReusableCellWithIdentifier:@"detailCell" forIndexPath:indexPath];

           stageCell.rightArr = self.stageRightArr;
           stageCell.leftArr = self.stageLeftArr;
           stageCell.cellType = StageCellTypeStge;
        return stageCell;
    }else if (cellType == DetailCellTypePayCell){
        GRPayDetailCell * payCell = [tableView dequeueReusableCellWithIdentifier:@"PayCell" forIndexPath:indexPath];
        payCell.payArr = self.payArr;
        
        payCell.orderPriceLabel.text = [NSString stringWithFormat:@"￥%.2lf", self.listModel.payMoney];
        return payCell;
    }else if (cellType == DetailCellTypeInvoiceCell){
        GRStageDetailTableViewCell * invoiceCell = [tableView dequeueReusableCellWithIdentifier:@"detailCell" forIndexPath:indexPath];
           invoiceCell.rightArr = self.invoiceRightArr;
            invoiceCell.leftArr = self.invoiceLeftArr;
           invoiceCell.cellType = StageCellTypeInvoice;
        return invoiceCell;
    }else {
        GRStageDetailTableViewCell * detailCell = [tableView dequeueReusableCellWithIdentifier:@"detailCell" forIndexPath:indexPath];
        detailCell.rightArr = self.orderRightArr;
        detailCell.leftArr = self.orderLeftArr;
        detailCell.cellType = StageCellTypeDetail;
        return detailCell;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    DetailCellType cellType = [self.CellArr[indexPath.section] integerValue];
    if (cellType == DetailCellTypeGoodsCell) {
        GROrderListGoodModel * listModel =self.listModel.goods[indexPath.row];
//        [GRGoodManagerViewController pushNewInstanceFromViewController:self goodsId:[NSString stringWithFormat:@"%ld",listModel.goodsId]];
    }
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
     DetailCellType cellType = [self.CellArr[section] integerValue];
    if (cellType == DetailCellTypeGoodsCell) {
        if (self.listModel.goods.count >2&&!self.listModel.lookMore) {
            return 2;
        }else{
            return self.listModel.goods.count;
        }
    }else{
        return 1;
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
     DetailCellType cellType = [self.CellArr[section] integerValue];
    if (cellType == DetailCellTypeGoodsCell) {
    GRConfirmSectionHeaderView * sectionHeaderView = [GRConfirmSectionHeaderView xx_instantiateFromNib];
        sectionHeaderView.vendorNameLabel.text = self.listModel.vendorName;
        sectionHeaderView.bkView.hidden = YES;
        return sectionHeaderView ;
        
    }else{
        return nil;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    DetailCellType cellType = [self.CellArr[indexPath.section] integerValue];
    if (cellType == DetailCellTypeStatusCell) {
        if (_listModel.status == 10 &&_listModel.isRefund == NO) {
            return 64;
        }else{
            return 116;
        }
      
    }else if (cellType == DetailCellTypeAddressCell){
        return 88;
    }else if(cellType == DetailCellTypeGoodsCell){
    return 130;
    }else if (cellType == DetailCellTypeStageCell){
         return 156;
    }else if (cellType == DetailCellTypePayCell){
       return 180;
    }else if (cellType == DetailCellTypeInvoiceCell){
        return 156;
    }else{
        return 110;
    }

  
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
     DetailCellType cellType = [self.CellArr[section] integerValue];
    if (cellType == DetailCellTypeGoodsCell) {
        return 45;
    }else{
    return 0.1 ;
    }
}


-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
     DetailCellType cellType = [self.CellArr[section] integerValue];
    if (cellType == DetailCellTypeGoodsCell) {
        GROderDetailFootView * footView = [GROderDetailFootView xx_instantiateFromNib];
        footView.delegate = self;
        footView.listModel = self.listModel;
        return footView;
    }else{
        UIView * footView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KscreenWidth, 10)];
        footView.backgroundColor = [UIColor clearColor];
        return footView;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    DetailCellType cellType = [self.CellArr[section] integerValue];
    if (cellType == DetailCellTypeGoodsCell) {
        CGFloat height = 55;
        if (_listModel.goods.count >2) {
            height += 45;
        }
        return height;
    }else{
    return 10;
    }
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.CellArr.count;

}

-(void)dealOrderWithActionType:(OrderActionType)actionType OrderId:(NSInteger)orderId{
    switch (actionType) {
        case OrderActionTypePayOrder:{
//            GRPayDetailViewController * payDetailVC = [[GRPayDetailViewController alloc]init];
//            payDetailVC.isOrderPay = YES;
//            payDetailVC.orderId = orderId;
//            [self.navigationController pushViewController:payDetailVC animated:YES];
        }
            break;
        case OrderActionTypeCancleOrder:{
            [[LFAlertBox defaultAlert]showAlertContent:@"是否取消订单" cancle:@"否" sure:@"是" completion:^(NSInteger index) {
                if (index) {
                    [self.detailAction returnMoney:orderId ResonType:0 CallBack:^(BOOL success) {
                        if (success) {
                            if (self.freshBlock != nil) {
                                self.freshBlock();
                            }
                            [self loadData];
                            GRPurchaseSuccessViewController * returnSuccessVC = [[GRPurchaseSuccessViewController alloc]init];
                            returnSuccessVC.successType = SuccessTypeCancleOrder;
                            [self.navigationController pushViewController:returnSuccessVC animated:YES];
                        }
                    }];
                }
            }];
        }
            break;
        case OrderActionTypeReturnMoeny:{
            returnOrderId = orderId;
           [GRReturnReasonView showGoodView:self IsReturnGood:NO];
        }
            break;
        case OrderActionTypeCustomerService:{
           [NSObject openSystemURL:@"telprompt://4006609727"];
        }
            break;
        case OrderActionTypeLogsticsProgress:{
            GRLogisticsInforViewController * logsticsVC = [[GRLogisticsInforViewController  alloc]init];
            logsticsVC.orderId = orderId;
            [self.navigationController pushViewController:logsticsVC animated:YES];
        }
            break;
        case OrderActionTypeConfirmOrder:{
            [self.detailAction confirmOrder:orderId CallBack:^(BOOL success) {
                if (success) {
                    if (self.freshBlock != nil) {
                        self.freshBlock();
                    }
                    [self loadData];
                }
            }];
        }
            break;
        case OrderActionTypeComment:{
            GROrderCommentViewController * commentVC = [[GROrderCommentViewController  alloc]init];
            commentVC.orderListModel = self.listModel;
            [self.navigationController pushViewController:commentVC animated:YES];
            
        }
            break;
            
        default:
            break;
    }
}

-(void)skipToReturnProgress:(NSInteger )orderId IsReturnGood:(BOOL)isReturnGood{
    GRReturnViewController  * returnVC =  [[GRReturnViewController alloc]init];
    returnVC.orderId  = orderId;
    returnVC.isReturnGood = isReturnGood;
    WEAKSELF
    returnVC.returnSuccess = ^{
        [weakSelf loadData];
    };
    [self.navigationController pushViewController: returnVC animated:YES];
    
}
-(void)applyReturnGood:(GROrderListGoodModel *)goodListModel DetailCell:(GROrderDetailGoodCell*)detailCell{

    [self.returnDic setObject:@(goodListModel.orderInfoId) forKey:@"orderInfoId"];
    if (goodListModel.quantity >1) {
        [GRReturnGoodView showGoodView:self MaxCount:goodListModel.quantity];
    }else{
        [_returnDic setObject:@(1) forKey:@"quantity"];
        [GRReturnReasonView showGoodView:self IsReturnGood:YES];
        
    }
    
}

-(void)returnGoodQuality:(NSInteger)quality{
     [self.returnDic setObject:@(quality) forKey:@"quantity"];
     [GRReturnReasonView showGoodView:self IsReturnGood:YES];
}

-(void)returnGoodReson:(GRReturnResonModel *)resonModel IsReturnGood:(BOOL)isReturnGood{
    if (isReturnGood) {
        [_returnDic setObject:resonModel.tex forKey:@"memo"];
        [self.returnDic setObject:@(resonModel.type) forKey:@"applyType"];
        [self.returnDic setObject:@(1) forKey:@"type"];
        [RequestManager applyOrderReturn:_returnDic CompleteHander:^(BOOL success, id responseObject, GRError *error) {
            if (success) {
                [self loadData];
                GRPurchaseSuccessViewController * returnSuccessVC = [[GRPurchaseSuccessViewController alloc]init];
                returnSuccessVC.successType = SuccessTypeReturnGood;
                [self.navigationController pushViewController:returnSuccessVC animated:YES];
                
            }else{
                [GRHUD showMessage:@"退货失败"];
            }
        }];
    }else{
        [self.detailAction  returnMoney:returnOrderId ResonType:resonModel.type CallBack:^(BOOL success) {
            if(success){
                if (self.freshBlock != nil) {
                    self.freshBlock();
                }
                [self loadData];
                GRPurchaseSuccessViewController * returnSuccessVC = [[GRPurchaseSuccessViewController alloc]init];
                returnSuccessVC.successType = SuccessTypeReturnMoney;
                [self.navigationController pushViewController:returnSuccessVC animated:YES];
            }
        }];
    }
}

-(void)showAllGood:(GROrderListModel *)listModel{
    listModel.lookMore = !listModel.lookMore;
    [self.detailList reloadSections:[NSIndexSet indexSetWithIndex:2] withRowAnimation:UITableViewRowAnimationAutomatic];
}

- (IBAction)orderTraceAction:(id)sender {
    [GROrderTraceView show:self.listModel.orderFollow];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
